﻿/*
Copyright (c) 2015 Adrian Ghirvu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace XRTools
{
    public class XRLexer
    {
        private enum State
        {
            START, OPEN, CLOSED, GUID, NUMBER, DOT, OPERATOR, BLOCK, MULTIPLE, IDENTIFIER
        }

        private class FunctionBlock
        {
            public int ParenthesisLevel;
            public int ParameterCount;
        }

        private const int PARAMETERNUMBER = 3;

        private State _state;
        private string _accumulator;
        private int _parenthesisLevel;
        private List<FunctionBlock> _functionBlocks;

        public List<string> Tokens { get; private set; }

        public XRLexer()
        {
            Initialize();
        }

        private void Initialize()
        {
            _state = State.START;
            _accumulator = String.Empty;
            _parenthesisLevel = 0;
            _functionBlocks = new List<FunctionBlock>();
            Tokens = new List<string>();
        }

        private void PushToken()
        {
            if (_accumulator.Length > 0)
            {
                Tokens.Add(_accumulator);                
            }
            _accumulator = String.Empty;
        }

        private void PushToken(char c)
        {
            Accumulate(c);
            PushToken();
        }

        private void Accumulate(char c)
        {
            _accumulator += c;
        }

        private bool IsAlphabetic(char c)
        {
            return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_');
        }

        private bool IsDigit(char c)
        {
            return (c >= '0' && c <= '9');
        }

        private bool IsWhiteSpace(char c)
        {
            return (c == '\t' || c == ' ' || c == '\n' || c == '\r');
        }

        private bool IsGuid(string guid)
        {
            Regex expression = new Regex("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
            return expression.IsMatch(guid);
        }

        private int OperationRecycle(char c)
        {
            if (IsWhiteSpace(c))
            {
                return 1;
            }
            return 0;
        }

        private int OperationWhiteSpace(char c)
        {
            if (IsWhiteSpace(c))
            {
                if (_state == State.NUMBER || _state == State.IDENTIFIER)
                {
                    PushToken();
                    _state = State.OPERATOR;
                    return 1;
                }
                return -1;
            }
            return 0;
        }

        private int OperationClose(char c)
        {
            if (c == ')')
            {
                if (_functionBlocks.Count > 0 && _functionBlocks[_functionBlocks.Count - 1].ParenthesisLevel == _parenthesisLevel)
                {
                    if (_functionBlocks[_functionBlocks.Count - 1].ParameterCount != PARAMETERNUMBER) return -1;
                    _functionBlocks.RemoveAt(_functionBlocks.Count - 1);
                }
                _parenthesisLevel--;
                if (_parenthesisLevel < 0) return -1;
                if (_state == State.NUMBER || _state == State.IDENTIFIER) PushToken();
                PushToken(c);
                _state = State.CLOSED;
                return 1;
            }
            return 0;
        }

        private int OperationBreak(char c)
        {
            if (c == ';')
            {
                if (_functionBlocks.Count < 1) return -1;
                if (_state == State.NUMBER || _state == State.IDENTIFIER) PushToken();
                PushToken(c);
                _functionBlocks[_functionBlocks.Count - 1].ParameterCount++; 
                _state = State.START;
                return 1;
            }
            return 0;
        }

        private bool AggregatorInit(char c)
        {
            if (c == '(')
            {
                PushToken(c);
                _parenthesisLevel++;
                _state = State.OPEN;
                return true;
            }
            if (c == '{')
            {
                Accumulate(c);
                _state = State.GUID;
                return true;
            }
            if (IsDigit(c))
            {
                Accumulate(c);
                _state = State.NUMBER;
                return true;
            }
            if (IsAlphabetic(c))
            {
                Accumulate(c);
                _state = State.IDENTIFIER;
                return true;
            }
            if (OperationRecycle(c) > 0) return true;
            return false;
        }

        private bool AggregatorOps(char c)
        {
            if(c =='+' || c == '-' || c == '*' || c == '/' || c == '?' || c == '&' || c == '|')
            {
                if (_state == State.NUMBER || _state == State.IDENTIFIER) PushToken();
                PushToken(c);
                _state = State.BLOCK;
                return true;
            }
            if (c == '<' || c == '=' || c == '>')
            {
                if (_state == State.NUMBER || _state == State.IDENTIFIER) PushToken();
                Accumulate(c);
                _state = State.BLOCK;
                return true;
            }
            return false;
        }

        private bool Interpret(char c)
        {
            int operationResult;
            switch (_state)
            {
                case State.START:
                    return AggregatorInit(c);
                case State.OPEN:
                    operationResult = OperationClose(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;                    
                    return AggregatorInit(c);
                case State.CLOSED:
                    operationResult = OperationClose(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;

                    operationResult = OperationBreak(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;                    
                    if (OperationRecycle(c) > 0) return true;
                    return AggregatorOps(c);
                case State.GUID:
                    if (IsAlphabetic(c))
                    {
                        Accumulate(c);
                        return true;
                    }
                    if (IsDigit(c))
                    {
                        Accumulate(c);
                        return true;
                    }
                    if (c == '-')
                    {
                        Accumulate(c);
                        return true;
                    }
                    if (c == '}')
                    {
                        Accumulate(c);
                        if (!IsGuid(_accumulator)) return false;
                        PushToken();
                        _state = State.OPERATOR;
                        return true;
                    }                    
                    return false;
                case State.NUMBER:
                    if (IsDigit(c))
                    {
                        Accumulate(c);
                        return true;
                    }
                    if (c == '.')
                    {
                        if (_accumulator.Contains(".")) return false;
                        Accumulate(c);
                        _state = State.DOT;
                        return true;
                    }
                    operationResult = OperationWhiteSpace(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;

                    if (AggregatorOps(c)) return true;
                    
                    operationResult = OperationClose(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;

                    operationResult = OperationBreak(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;

                    return false;
                case State.DOT:
                    if (IsDigit(c))
                    {
                        Accumulate(c);
                        _state = State.NUMBER;
                        return true;
                    }
                    return false;
                case State.OPERATOR:
                    if (AggregatorOps(c)) return true;

                    operationResult = OperationWhiteSpace(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;
                    
                    operationResult = OperationClose(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;

                    operationResult = OperationBreak(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;
                    return false;
                case State.BLOCK:
                    if (c == '>')
                    {
                        if (_accumulator != "<") return false;
                        PushToken(c);
                        _state = State.MULTIPLE;
                        return true;
                    }
                    if (c == '=')
                    {
                        if (_accumulator != "<" && _accumulator != "=" && _accumulator != ">")
                        {
                            return false;
                        }
                        PushToken(c);
                        _state = State.MULTIPLE;
                        return true;
                    }
                    if (_accumulator == "=") return false;
                    if (_accumulator == "<" || _accumulator == ">") PushToken();
                    return AggregatorInit(c);
                case State.MULTIPLE:
                    return AggregatorInit(c);
                case State.IDENTIFIER:
                    if (IsAlphabetic(c))
                    {
                        Accumulate(c);
                        return true;
                    }
                    if (c == '(')
                    {
                        PushToken();
                        PushToken(c);
                        _parenthesisLevel++;
                        _functionBlocks.Add(new FunctionBlock { ParenthesisLevel = _parenthesisLevel, ParameterCount = 1 });
                        _state = State.OPEN;
                        return true;
                    }

                    if (AggregatorOps(c)) return true;

                    operationResult = OperationWhiteSpace(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;

                    operationResult = OperationClose(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;

                    operationResult = OperationBreak(c);
                    if (operationResult > 0) return true;
                    if (operationResult < 0) return false;

                    return false;
                default:
                    return false;
            }
        }

        public bool Tokenize(string expression)
        {
            Initialize();
            if (expression == null) return false;
            for (int i = 0; i < expression.Length; i++)
            {
                if (!Interpret(expression[i])) return false;
            }
            if (_state == State.NUMBER || _state == State.IDENTIFIER) PushToken();
            if (_parenthesisLevel != 0) return false;
            if (_state == State.OPEN || _state == State.GUID || _state == State.DOT || _state == State.BLOCK || _state == State.MULTIPLE) return false;
            return true;
        }
    }
}
